<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '报检单',
    enablePullDownRefresh: false,
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <view>
    <page-meta :root-font-size="setting.rootFontSize"></page-meta>
    <view style="display: flex; flex-direction: column; height: 100vh; background-color: #f2f2f1">
      <view style="position: sticky; top: 0; z-index: 9999">
        <wd-navbar
          :title="`${assayType === 'qcMiddleCheck' ? '实验报检单' : '任务报检单'}`"
          :bordered="false"
          safeAreaInsetTop
        >
          <template #left>
            <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
          </template>
        </wd-navbar>
      </view>
      <view class="actions-bar">
        <th-button
          size="small"
          class="btn"
          type="text"
          v-if="checkPremiss(`qc_${assayType}_edit`)"
          :disabled="![0, 3].includes(form.status) || form.taskAllStatus !== '1'"
          @click="onSave"
        >
          保存
        </th-button>
        <th-button
          size="small"
          class="btn"
          type="text"
          v-if="checkPremiss(`qc_${assayType}_submit`)"
          :disabled="!form.id || ![0, 3].includes(form.status) || form.taskAllStatus !== '1'"
          @click="onSubmit"
        >
          提交
        </th-button>
        <th-button
          size="small"
          class="btn"
          type="text"
          v-if="checkPremiss(`qc_${assayType}_revoke`)"
          :disabled="!form.id || form.status !== 1 || form.taskAllStatus !== '1'"
          @click="handleShow('revoke')"
        >
          撤回
        </th-button>
        <th-button
          size="small"
          class="btn"
          type="text"
          v-if="checkPremiss(`qc_${assayType}_revive`)"
          :disabled="!form.id || form.status !== 2 || form.taskAllStatus !== '1'"
          @click="handleShow('revive')"
        >
          弃审
        </th-button>
        <block v-if="form.status === 1 && checkPremiss(`qc_${assayType}_check`)">
          <th-button
            v-if="form.instanceId"
            :disabled="!form.taskId || form.taskAllStatus !== '1'"
            type="text"
            @click="handleShow('complete')"
            size="small"
          >
            审核
          </th-button>
          <th-button
            v-else
            type="text"
            @click="onComplete(2)"
            :disabled="form.taskAllStatus !== '1'"
          >
            审核
          </th-button>
        </block>
        <block v-if="form.status === 2">
          <text>|</text>
          <th-button
            size="small"
            :disabled="form.flag === 1 || form.taskAllStatus !== '1'"
            class="btn"
            type="text"
            @click="toReport"
          >
            报告
          </th-button>
          <uni-print-button
            size="small"
            class="btn"
            type="text"
            :disabled="!form.checkCode"
            :kind="assayType"
            :data="[{...form}]"
          >
            打印条码
          </uni-print-button>
        </block>
      </view>
      <view style="display: flex; flex: 1; flex-direction: column; height: 0">
        <view style="flex: 1; overflow: auto">
          <th-card title="基础信息">
            <wd-form ref="formRef" :model="form">
              <th-form>
                <th-form-item label="报检单号">
                  <view class="text seq-no-text">
                    {{ form.checkCode }}
                  </view>
                </th-form-item>
                <th-form-item label="报检日期">
                  <view v-if="[0, 3].includes(form.status)" class="text seq-no-text">
                    <th-datetime-picker
                      v-model:value="form.checkDate"
                      format="YYYY-MM-DD"
                      placeholder="请选择日期"
                    ></th-datetime-picker>
                  </view>
                  <text v-else>{{ form.checkDate }}</text>
                </th-form-item>
                <th-form-item label="报检人">
                  <view class="text seq-no-text">
                    {{ form.inspectName }}
                  </view>
                </th-form-item>
                <th-form-item label="任务编码">
                  <view class="text seq-no-text">
                    {{ form.taskCode }}
                  </view>
                </th-form-item>
                <th-form-item label="产品名称">
                  <view class="text seq-no-text">
                    {{ form.invName }}
                  </view>
                </th-form-item>
                <th-form-item label="产品规格">
                  <view class="text seq-no-text">
                    {{ form.invStd }}
                  </view>
                </th-form-item>
                <th-form-item label="样品编码">
                  <view class="text seq-no-text">
                    {{ form.sampleCode }}
                  </view>
                </th-form-item>
                <th-form-item label="检验类型">
                  <view class="text seq-no-text">
                    <text v-if="form.type === 0">中控</text>
                    <text v-else-if="form.type === 1">终检</text>
                    <text v-else>{{ form.type }}</text>
                  </view>
                </th-form-item>
                <block v-if="assayType === 'qcMiddleCheck'">
                  <th-form-item label="取样时间">
                    <view v-if="[0, 3].includes(form.status)" class="text seq-no-text">
                      <th-datetime-picker
                        v-model:value="form.sampleTime"
                        format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择日期"
                      ></th-datetime-picker>
                    </view>
                    <text v-else>{{ form.sampleTime }}</text>
                  </th-form-item>
                  <th-form-item label="取样位置">
                    <view class="text seq-no-text">
                      <template v-if="form.status == 0">
                        <wd-input
                          type="text"
                          prop="position"
                          v-model="form.position"
                          placeholder="请输入取样位置"
                          no-border
                        />
                      </template>
                      <template v-else>{{ form.position }}</template>
                    </view>
                  </th-form-item>
                  <th-form-item label="取样工序">
                    <view class="text seq-no-text">
                      {{ form.processName }}
                    </view>
                  </th-form-item>
                </block>
                <th-form-item label="样品批号">
                  <th-input
                    v-if="assayType === 'qcMiddleChecks' && [0, 3].includes(form.status)"
                    v-model:value="form.sampleBatch"
                    placeholder="请选择或输入"
                    :validate="[{ required: true, trigger: 'change', message: '请输入样品批号' }]"
                    clearable
                    border
                    ref="sampleBatch"
                    style=" width: 100%;margin-left: -10rpx"
                  ></th-input>
                  <view class="text seq-no-text">
                    {{ form.sampleBatch }}
                  </view>
                </th-form-item>

                <th-form-item label="单据状态">
                  <view class="text seq-no-text">
                    <wd-tag
                      :bg-color="getStatus(form.status)['color']"
                      :color="getStatus(form.status)['color']"
                      plain
                    >
                      {{ getStatus(form.status)['label'] }}
                    </wd-tag>
                  </view>
                </th-form-item>

                <th-form-item label="实验记录单号" v-if="assayType === 'qcMiddleCheck'">
                  <view class="text seq-no-text">
                    {{ form.recordNo }}
                  </view>
                </th-form-item>
				<th-form-item label="分析手段" v-if="form.analysis">
				  <view class="text seq-no-text">
				    {{ form.analysis }}
				  </view>
				</th-form-item>
              </th-form>
            </wd-form>
          </th-card>
          <th-card title="检测项目">
            <view style="margin-bottom: 10rpx">
              <th-button
                type="primary"
                v-if="form.status === 0"
                @click="addRow"
                style="margin-right: 15rpx"
              >
                新增一行
              </th-button>
              <uni-print-button
                :disabled="!form.checkCode || printData.length === 0"
                :kind="assayType"
                :data="printData"
              >
                打印条码
              </uni-print-button>
            </view>
            <th-table
              v-if="form[assayKey]"
              :columns="columns"
              stripe
              multiple
              :dataList="form[assayKey]"
              ref="multipleTable"
            >
              <template v-slot:analysisId="{ scope }">
                <th-select
                  v-if="[0, 3].includes(form.status)"
                  v-model:value="scope.row.analysisId"
                  placeholder="请选择分析手段"
                  :options="scope.row.baseAnalysisDTOS || analysisOptions"
                  border
                  :validate="[{ required: true, trigger: 'change', message: '请选择分析手段' }]"
                  :ref="`analysisId${scope.$index}`"
                  @change="changeanalysisId(scope.row)"
                  style="width: 300rpx"
                ></th-select>
                <text v-else>{{ scope.row.analysisName }}</text>
              </template>
              <template v-slot:itemName="{ scope }">
                <view
                  v-if="[0, 3].includes(form.status) && !scope.row.baseAnalysisDTOS"
                  style="display: flex; align-items: center; text-align: left"
                >
                  <th-input
                    v-model:value="scope.row.itemName"
                    placeholder="请选择或输入"
                    border
                    :validate="[
                      { required: true, trigger: 'change', message: '请选择或选择检测指标' },
                    ]"
                    clearable
                    :ref="`itemName${scope.$index}`"
                    @input="scope.row.valueType || (scope.row.valueType = '文本')"
                  ></th-input>
                  <wd-icon
                    name="arrow-down"
                    size="22px"
                    @click="showItemNameList(scope.row, scope.$index)"
                  ></wd-icon>
                </view>
                <text v-else>{{ scope.row.itemName }}</text>
              </template>
              <!-- 值类型 -->
              <template v-slot:valueType="{ scope }">
                <th-select
                  v-if="[0, 3].includes(form.status)"
                  v-model:value="scope.row.valueType"
                  placeholder="请选择分析手段"
                  :options="valueTypeOptions"
                  border
                ></th-select>
                <text v-else>{{ scope.row.valueType }}</text>
              </template>
              <template v-slot:unit="{ scope }">
                <th-select
                  v-if="[0, 3].includes(form.status)"
                  :options="
                    scope.row.analysisIndexUnitList?.map((item) => {
                      return { label: item, value: item };
                    })
                  "
                  border
                  v-model:value="scope.row.unit"
                ></th-select>
                <text v-else>{{ scope.row.unit }}</text>
              </template>
              <template v-slot:equipmentCode="{ scope }">
                <th-select
                  v-if="[0, 3].includes(form.status)"
                  :options="
                    scope.row.equipmentEntities?.map((item) => {
                      return { label: item.equipmentName, value: item.equipmentCode };
                    })
                  "
                  border
                  v-model:value="scope.row.equipmentCode"
                  @change="changeEquiment(scope.row)"
                ></th-select>
                <text v-else>{{ scope.row.equipmentName }}</text>
              </template>
              <!-- 化验员 -->
              <template v-slot:assayerName="{ scope }">
                <view class="assay-name" @click="showAssayerName(scope.row.assayerName)">
                  {{ scope.row.assayerName }}
                </view>
              </template>

              <template v-slot:remark="{ scope }">
                <th-input
                  v-if="[0, 3].includes(form.status)"
                  v-model:value="scope.row.remark"
                  placeholder="请输入描述"
                  border
                  mode="textarea"
                  clearable
                  autoHeight
                  ref="remark"
                ></th-input>
                <view v-else style="text-align: center">{{ scope.row.remark }}</view>
              </template>
              <template v-slot:action="{ scope }">
                <text
                  style="margin-right: 10rpx; color: #0081ff"
                  @click="copyRow(scope.row, scope.$index)"
                >
                  复制
                </text>
                <text
                  :style="{ color: scope.row.editFlag ? 'red' : '#909399' }"
                  @click="delRow(scope.row, scope.$index)"
                >
                  删除
                </text>
              </template>
            </th-table>
          </th-card>

          <th-card
            title="审核信息"
            v-if="form.status == '1' || form.status == '2' || form.status == '3'"
          >
            <view class="row-list">
              <view>
                <flowTable
                  ref="flowDetailsTableRef"
                  :processInstanceId="form.instanceId"
                ></flowTable>
              </view>
            </view>
          </th-card>
        </view>
      </view>
    </view>
    <!-- 审批 -->
    <th-dialog v-model:visible="commentShow">
      <template v-slot:content>
        <th-input
          v-model:value="comment"
          mode="textarea"
          autoheight
          placeholder="请填写原因"
          style="padding: 10rpx 0"
        ></th-input>
      </template>
      <template v-slot:footer>
        <view class="btn_group">
          <view class="btn" @click="handleClose">取消</view>
          <view class="btn" style="color: #409eff" v-if="action === 'revoke'" @click="onRevoke">
            撤回
          </view>
          <view class="btn" style="color: #409eff" v-if="action === 'revive'" @click="onRevive">
            弃审
          </view>
          <view class="btn" style="color: #f50" v-if="action === 'complete'" @click="onComplete(3)">
            拒绝
          </view>
          <view
            class="btn"
            style="color: #409eff"
            v-if="action === 'complete'"
            @click="onComplete(2)"
          >
            同意
          </view>
        </view>
      </template>
    </th-dialog>
    <!-- 化验员 -->
    <th-dialog v-model:visible="assayerNameShow" align="middle" width="80%">
      <template v-slot:content>
        <view style="padding: 30rpx; line-height: 40rpx">{{ assayerNames }}</view>
      </template>
    </th-dialog>
    <wd-action-sheet
      v-model="showItemName"
      :actions="itemNamcolumns"
      @close="closeItemNam"
      @select="selectItemNam"
    />
  </view>
</template>

<script lang="ts" setup>
import { nextTick } from 'process';
import { useSetting } from '@/stores/setting';
import {
  formInfoByTask,
  ccFormInfoByExperimentRecord,
  analysisList,
  formSave,
  formUpdate,
  formInfo,
  formSubmit,
  revokeProcess,
  formComplete,
  formRevive,
  getInfoBarCode,
  ccRetInfoBarCode,
  getFormInfoVersion,
  getAssayers,
} from '@/service/pm-assay';
import { formatByDayjs } from '@/utils/util';
import { useUserStore } from '@/stores/user';
import { useDict } from '@/hooks/dict';
import { listLastNodePerson } from '@/service/pm-requirement';
// import printButton from '../assay-report/component/printButton.vue';
// import { printMiddleCheck, printExoticCheck } from '@/utils/print';
import showModal from '@/utils/modal';
import thTable from '../assay-report/component/th-table.vue';
import thInput from '../assay-report/component/th-input.vue';
import thButton from '../assay-report/component/th-button.vue';
import thSelect from '../assay-report/component/th-select.vue';
import thDatetimePicker from '../assay-report/component/th-datetime-picker.vue';
import thDialog from '../assay-report/component/th-dialog.vue';
import UniPrintButton from '../assay-report/component/uniPrintButton.vue';

const assayType = ref();
const assayKey = ref();
const setting = useSetting();
const emits = defineEmits(['refresh']);
const userStore: any = useUserStore();
const flowDetailsTableRef: any = ref({});

const { proxy } = getCurrentInstance();

const toReport = async () => {
  const { checkCode } = form.value;
  uni.showLoading({
    title: '等待跳转',
    mask: true,
  });
  (assayType.value === 'qcExoticCheck' ? getInfoBarCode(checkCode) : ccRetInfoBarCode(checkCode))
    .then((res) => {
      if (res.code === 0) {
        uni.navigateTo({
          url: `/pages/pm/assay-report/form?t=${
            assayType.value === 'qcExoticCheck' ? 'qcExoticReport' : 'qcMiddleReport'
          }&checkCode=${checkCode}`,
        });
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    })
    .catch((err) => {
      uni.showToast({
        title: err.msg,
        icon: 'none',
      });
    })
    .finally(() => {
      uni.hideLoading();
    });
};

const checkPremiss = (k) => {
  return userStore.userInfos.authBtnList.some((v: string) => v === k);
};
// 提交表单数据
const form = ref({
  id: '',
  pid: '', // 研发任务id
  version: undefined,
  checkCode: '',
  inspectName: '',
  checkDate: formatByDayjs(new Date(), 'YYYY-MM-DD'),
  taskCode: '',
  invName: '',
  sampleCode: '',
  sampleBatch: '',
  invStd: '',
  invBatch: '',
  processName: '',
  sampleTime: formatByDayjs(new Date(), 'YYYY-MM-DD HH:mm:ss'),
  position: '',
  recordId: '',
  recordNo: '',
  type: 0,
  status: undefined,
  instanceId: '',
  taskId: null,
  flag: undefined,
  cusFlag: undefined,
  taskAllStatus: undefined,
  qcMiddleChecksList: undefined,
  qcExoticChecksList: undefined,
  analysis:''
});

// 打印
const printData = ref([]);
watch(
  () => form.value,
  (n) => {
    const { invName, checkCode, sampleCode, sampleBatch, processName, position, invStd } =
      form.value;
    printData.value = n[assayKey.value]
      ? n[assayKey.value]
          .filter((item) => item.checked)
          .map((item) => {
            return {
              invName,
              checkCode,
              sampleCode,
              sampleBatch,
              processName,
              position,
              invStd,
              itemName: item.itemName,
            };
          })
      : [];
  },
  {
    deep: true,
  },
);

const valueTypeOptions = ref([
  {
    label: '文本',
    value: '文本',
  },
  {
    label: '数字',
    value: '数字',
  },
  {
    label: '是否',
    value: '是否',
  },
]);

const baseColumns = [
  { label: '选择', type: 'selection', align: 'center', width: 40, fixed: true },
  { label: '序号', type: 'index', align: 'center', width: 40, fixed: true },
  {
    label: '检测项目（分析手段)',
    prop: 'analysisId',
    width: 160,
    align: 'center',
    render: 'analysisId',
  },
  { label: '检测指标', prop: 'itemName', align: 'center', width: 200, render: 'itemName' },
  { label: '值类型', prop: 'valueType', align: 'center', width: 120, render: 'valueType' },
  { label: '指标单位', prop: 'unit', align: 'center', width: 120, render: 'unit' },
  {
    label: '检测设备',
    prop: 'equipmentCode',
    align: 'center',
    width: 200,
    render: 'equipmentCode',
  },
  {
    label: '化验员',
    prop: 'assayerName',
    align: 'center',
    width: 120,
    render: 'assayerName',
  },
  {
    label: '描述',
    prop: 'remark',
    width: 200,
    render: 'remark',
  },
];

const columns = computed(() => {
  if (form.value.status === 0 || form.value.status === 3) {
    return [
      ...baseColumns,
      {
        label: '操作',
        type: 'action',
        align: 'center',
        render: 'action',
        width: 80,
        fixed: 'right',
      },
    ];
  }

  return baseColumns;
});

const init = (id: string, checkCode: string) => {
  uni.showLoading({
    mask: true,
  });

  if (checkCode) {
    formInfo(assayType.value, id)
      .then((res) => {
        form.value[assayKey.value] = res.data[assayKey.value]?.map((item) => {
          // const o = analysisOptions.value.find((opt) => opt.value === item.analysisId);
          // item.equipmentEntities = o?.equipmentList || [];
          // item.indexEntities = o?.analysisIndexList || [];
          if (item.equipmentCode) {
            const match = item.equipmentEntities.find(
              (equ: any) => equ.equipmentCode === item.equipmentCode,
            );
            if (match) {
              item.assayerName = match.userCodeList
                ? match.userCodeList
                    .map((item: any) => {
                      return item.nickName;
                    })
                    .join(',')
                : '';
              item.assayerCode = match.userCodeList
                ? match.userCodeList
                    .map((item: any) => {
                      return item.userCode;
                    })
                    .join(',')
                : '';
            } else {
              item.equipmentCode = undefined;
              item.equipmentName = undefined;
            }
          }
          // 回显分析手段
          item.baseAnalysisDTOS = item.baseAnalysisDTOS?.map((item) => {
            return { label: item.analysisName, value: item.id };
          });
          return item;
        });
        form.value.id = res.data.id;
        form.value.pid = res.data.pid;
        form.value.checkDate = res.data.checkDate;
        form.value.taskId = res.data.taskId;
        form.value.instanceId = res.data.instanceId;
        form.value.sampleTime = res.data.sampleTime;
        form.value.version = res.data.version;
        if (res.data.cusFlag) {
          columns.value.splice(4, 0, {
            label: '需求指标',
            prop: 'standardValuePm',
            width: 140,
            align: 'center',
          } as any);
        }
        fillInfo(res);
        if (form.value.instanceId) {
          nextTick(() => {
            flowDetailsTableRef.value.getFlowDetails();
          });
          getCancelApprover();
        }
      })
      .finally(() => {
        commentShow.value = false;
        comment.value = '';
        uni.hideLoading();
      });
  }
};
// 根据编码获取化验员列表
const getAssayersList = (code: string) => {
  return new Promise((resolve) => {
    getAssayers(code)
      .then((res) => {
        if (res.code === 0) {
          resolve(res.data);
        } else {
          resolve([]);
        }
      })
      .catch(() => {
        resolve([]);
      });
  });
};

const fillInfo = (res) => {
  const {
    type,
    checkCode,
    recordId,
    recordNo,
    inspectName,
    taskCode,
    invName,
    position,
    processName,
    sampleCode,
    sampleBatch,
    invBatch,
    status,
    flag,
    invStd,
    taskAllStatus,
	analysis
  } = res.data;
  form.value.type = type;
  form.value.recordId = recordId;
  form.value.recordNo = recordNo;
  form.value.checkCode = checkCode;
  form.value.inspectName = inspectName;
  form.value.taskCode = taskCode;
  form.value.invName = invName;
  form.value.position = position;
  form.value.processName = processName;
  form.value.sampleCode = sampleCode;
  form.value.sampleBatch = sampleBatch;
  form.value.invStd = invStd;
  form.value.invBatch = invBatch;
  form.value.status = status;
  form.value.flag = flag;
  form.value.taskAllStatus = taskAllStatus;
  form.value.analysis = analysis;
};

// const printCode = () => {
//   if (assayType.value === 'qcMiddleCheck') {
//     printMiddleCheck(form.value);
//   } else {
//     printExoticCheck(form.value);
//   }
// };

const changeanalysisId = async (item: any, from?: string) => {
  if (!item.baseAnalysisDTOS && !from) {
    item.itemName = '';
  }
  item.unit = '';
  item.equipmentCode = undefined;
  item.equipmentName = undefined;
  const o = analysisOptions.value.find((a) => a.value === item.analysisId);
  item.equipmentEntities = o?.equipmentList || [];
  item.indexEntities = o?.analysisIndexEntityList || [];
  item.analysisName = o?.label;
  item.analysisIndexUnitList = o?.analysisIndexUnit?.split(',');
  if (item.analysisIndexUnitList && item.analysisIndexUnitList.length) {
    item.unit = item.analysisIndexUnitList?.[0];
  }
  if (item.equipmentEntities && item.equipmentEntities.length) {
    const { equipmentCode, equipmentName, userCodeList } = item.equipmentEntities[0];
    item.equipmentCode = equipmentCode;
    item.equipmentName = equipmentName;
    if (userCodeList) {
      // 根据设备编码获取化验员
      item.assayerName = userCodeList
        .map((itm) => {
          return itm.nickName;
        })
        .join(',');
      item.assayerCode = userCodeList
        .map((itm) => {
          return itm.userCode;
        })
        .join(',');
    } else {
      // 根据设备编码获取化验员
      const arr = await getAssayersList(equipmentCode);
      item.assayerName = (arr as [])
        .map((item: any) => {
          return item.nickName;
        })
        .join(',');
      item.assayerCode = (arr as [])
        .map((item: any) => {
          return item.userCode;
        })
        .join(',');
    }
  } else {
    item.assayerName = '';
    item.assayerCode = '';
  }
};

const analysisOptions = ref([]);
onLoad(async (options) => {
  const { id, checkCode, type, t } = options;
  assayType.value = t || (type === undefined ? 'qcExoticCheck' : 'qcMiddleCheck');

  assayKey.value =
    assayType.value === 'qcMiddleCheck' ? 'qcMiddleChecksList' : 'qcExoticChecksList';

  // 获取分析手段
  await analysisList({ size: 20000 }).then((res) => {
    analysisOptions.value = res.data.records.map((item) => {
      const { analysisName, id, equipmentList, analysisIndexUnit, analysisIndexEntityList } = item;
      return {
        label: analysisName,
        value: id,
        equipmentList,
        analysisIndexUnit,
        analysisIndexEntityList,
      };
    });
  });

  if (checkCode) {
    // 详情 修改
    init(id, checkCode);
  } else if (type === undefined) {
    // 新增
    getFormInfoVersion({ taskId: id })
      .then((res) => {
        if (res.code === 0) {
          const version = res.data[0]?.version || 0;
          // 外来样
          formInfoByTask(id, version).then(async (res) => {
            if (res.code !== 0) {
              uni.showToast({
                title: res.msg,
                icon: 'none',
              });
              return;
            }
            const { id, type, taskType, analysisDTOS, baseAnalysisIndexDTOS } = res.data;
            form.value.pid = id;
            form.value.type = type;
            form.value.version = version;

            if (taskType === 30 || taskType === 6) {
              // 直接取样检测 新增
              for (let i = 0; i < baseAnalysisIndexDTOS.length; i++) {
                const item = baseAnalysisIndexDTOS[i];
                const row = {
                  need: true,
                  analysisName: undefined,
                  analysisId: undefined,
                  itemName: item.itemName,
                  valueType: item.valueType,
                  unit: undefined,
                  equipmentName: undefined,
                  equipmentCode: undefined,
                  remark: '',
                  equipmentEntities: [],
                  indexEntities: [],
                  assayerName: undefined,
                  baseAnalysisDTOS: item.baseAnalysisDTOS?.map((item) => {
                    return { label: item.analysisName, value: item.id };
                  }),
                };

                // 如果刚好有一个分析手段，则默认。并回显化员
                if (item.baseAnalysisDTOS && item.baseAnalysisDTOS.length === 1) {
                  row.analysisId = item.baseAnalysisDTOS[0].id;
                  row.analysisName = item.baseAnalysisDTOS[0].analysisName;
                  await changeanalysisId(row);
                }

                form.value.qcExoticChecksList.push(row);
              }
            } else if (analysisDTOS) {
              // 外来样检测 新增
              analysisDTOS.forEach((row: any) => {
                if (row.equipmentEntities && row.equipmentEntities.length) {
                  const { equipmentCode, equipmentName, userCodeList } = row.equipmentEntities[0];
                  row.equipmentCode = equipmentCode;
                  row.equipmentName = equipmentName;
                  // 有人员则赋值，无人员则空值
                  if (userCodeList) {
                    row.assayerName = userCodeList
                      .map((item) => {
                        return item.nickName;
                      })
                      .join(',');
                    row.assayerCode = userCodeList
                      .map((item) => {
                        return item.userCode;
                      })
                      .join(',');
                  }
                }
                if (row.analysisIndexUnitList && row.analysisIndexUnitList.length === 1) {
                  row.unit = row.analysisIndexUnitList?.[0];
                }
              });
              form.value.qcExoticChecksList = analysisDTOS;
              fillInfo(res);
            }
          });
        }
      })
      .catch((err) => {
        uni.showToast({
          title: err.msg,
          icon: 'none',
        });
      });
  } else {
    // 实验
    ccFormInfoByExperimentRecord(id, type)
      .then(async (res) => {
        if (res.code === 0) {
          form.value.pid = id;
          fillInfo(res);
          const { paramList, baseAnalysisIndexDTOS } = res.data;
          form.value.checkDate = res.data.checkDate
            ? formatByDayjs(res.data.checkDate, 'YYYY-MM-DD')
            : formatByDayjs(new Date(), 'YYYY-MM-DD');
          form.value.qcMiddleChecksList = res.data.qcMiddleChecksList || [];

          if (paramList && paramList.length) {
            // 中控
            for (let i = 0; i < paramList.length; i++) {
              const item = paramList[i];
              const row = {
                need: true,
                analysisName: item.analysisName,
                analysisId: item.analysisId,
                itemName: item.paramName,
				valueType:item.valueType,
                unit: undefined,
                equipmentName: undefined,
                equipmentCode: undefined,
                remark: '',
                assayerName: '',
                assayerCode: '',
                equipmentEntities: [],
                indexEntities: [],
              };
              await changeanalysisId(row, 'paramList');
              // if (row.equipmentCode) {
              //   // eslint-disable-next-line no-await-in-loop
              //   row.assayerName = (await getAssayersList(row.equipmentCode)) as string;
              // }
              form.value.qcMiddleChecksList.push(row);
            }
          } else if (baseAnalysisIndexDTOS && baseAnalysisIndexDTOS.length) {
            columns.value.splice(4, 0, {
              label: '需求指标',
              prop: 'standardValuePm',
              width: 140,
              align: 'center',
            } as any);
            form.value.cusFlag = 1;
            for (let i = 0; i < baseAnalysisIndexDTOS.length; i++) {
              const item = baseAnalysisIndexDTOS[i];
              const row = {
                need: true,
                analysisName: '',
                analysisId: '',
                itemName: item.itemName,
				valueType:item.valueType,
                unit: undefined,
                equipmentName: undefined,
                equipmentCode: undefined,
                standardValuePm: item.standardValuePm,
			          standardValue: item.standardValue,
                remark: '',
                equipmentEntities: [],
                indexEntities: [],
                assayerName: undefined,
                assayerCode: undefined,
                baseAnalysisDTOS: item.baseAnalysisDTOS?.map((item) => {
                  return { label: item.analysisName, value: item.id };
                }),
              };

              if (item.baseAnalysisDTOS && item.baseAnalysisDTOS.length === 1) {
                row.analysisId = item.baseAnalysisDTOS[0].id;
                row.analysisName = item.baseAnalysisDTOS[0].analysisName;
                await changeanalysisId(row);
              }

              // if (row.equipmentCode) {
              //   // eslint-disable-next-line no-await-in-loop
              //   row.assayerName = (await getAssayersList(row.equipmentCode)) as string;
              // }

              form.value.qcMiddleChecksList.push(row);
            }
          } else {
            addRow();
          }
        } else {
          uni.showToast({
            mask: true,
            icon: 'none',
            title: `获取数据失败，失败原因${res.msg}`,
          });
        }
      })
      .catch((err) => {
        uni.showToast({
          mask: true,
          icon: 'none',
          title: `获取数据失败，失败原因${err.msg}`,
        });
      });
  }
});

const goBack = () => {
  uni.navigateBack();
};

const formRef: any = ref({});
const onSave = (ref) => {
  const formData = {
    ...form.value,
  };
  let checkUser = [];
  const checksList = form.value[assayKey.value].map((item) => {
    const {
      analysisName,
      analysisId,
      valueType,
      itemName,
      unit,
      standardValuePm,
	    standardValue,
      remark,
      editFlag,
      equipmentCode,
      equipmentName,
      assayerName,
      assayerCode,
    } = item;
    const assayerCodeArr = assayerCode ? assayerCode.split(',') : [];
    checkUser = [...checkUser, ...assayerCodeArr];
    return {
      analysisName,
      analysisId,
      valueType,
      itemName,
      unit,
      standardValuePm,
	    standardValue,
      equipmentCode,
      equipmentName,
      remark,
      editFlag,
      assayerName,
      assayerCode,
    };
  });
  formData.checkUser = [...new Set(checkUser)].join(',');
  formData[assayKey.value] = checksList;
  // 校验表单
  const validate = Object.keys(proxy.$refs).filter((key) => {
    const el = proxy.$refs[key] as any;
    if (el && el.validate) {
      return !el.validate();
    }
    return false;
  });

  if (validate.length) {
    uni.showToast({
      title: '请完善必填项',
      icon: 'none',
    });
    return;
  }

  if (ref !== 'submit') {
    // 如果是提交触发保存则不加loading
    uni.showLoading({
      title: '保存中',
      mask: true,
    });
  }

  (form.value.id ? formUpdate(assayType.value, formData) : formSave(assayType.value, formData))
    .then((res) => {
      if (res.code === 0) {
        if (ref !== 'submit') {
          uni.showToast({
            mask: true,
            title: `保存成功`,
            icon: 'none',
          });
          uni.$emit('assayFormRefresh', true);
          init(res.data.id, res.data.checkCode);
        } else {
          // 回调提交
          onSubmit();
        }
      } else {
        uni.showToast({
          mask: true,
          title: `保存失败，失败原因${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      commentShow.value = false;
      comment.value = '';
      uni.hideLoading();
    });
};

// 刷新流转详情
const refreshFlow = () => {
  if (form.value.instanceId) {
    nextTick(() => {
      flowDetailsTableRef.value.getFlowDetails();
    });
    getCancelApprover();
  }
};

const formSubmitHandle = () => {
  setTimeout(() => {
    uni.showLoading({
      title: '提交中',
      mask: true,
    });
    formSubmit(assayType.value, { id: form.value.id })
      .then((res) => {
        if (res.code === 0) {
          uni.showToast({
            mask: true,
            title: `单据${form.value.checkCode}提交成功`,
            icon: 'none',
          });
          uni.$emit('assayFormRefresh', true);
          init(form.value.id, form.value.checkCode);
          refreshFlow();
        } else {
          uni.showToast({
            mask: true,
            title: `单据${form.value.checkCode}提交失败，失败原因：${res.msg}`,
            icon: 'none',
          });
        }
      })
      .finally(() => {
        commentShow.value = false;
        comment.value = '';
        uni.hideLoading();
      });
  });
};

const onSubmit = (e?: any) => {
  if (e) {
    showModal({
      title: '提示',
      content: '是否提交该单据',
      showCancel: true,
      confirm: () => {
        // 编辑模式 提交前先保存
        if (e) {
          onSave('submit');
          return;
        }
        formSubmitHandle();
      },
    });
  } else {
    // 保存后回调 不弹窗
    formSubmitHandle();
  }
};

// 撤回
const comment = ref('');
const action = ref('');
const commentShow = ref(false);
const handleClose = () => {
  comment.value = '';
  commentShow.value = false;
};
const handleShow = (type) => {
  action.value = type;
  commentShow.value = true;
};

const onRevoke = () => {
  showModal({
    title: '提示',
    content: '是否撤回该单据',
    showCancel: true,
    confirm: () => {
      uni.showLoading({
        title: '撤回中',
        mask: true,
      });
      revokeProcess(assayType.value, {
        id: form.value.id,
        comment: comment.value,
      })
        .then((res) => {
          if (res.code === 0) {
            uni.showToast({
              mask: true,
              title: `单据${form.value.checkCode}撤回成功`,
              icon: 'none',
            });
            uni.$emit('assayFormRefresh', true);
            handleClose();
            init(form.value.id, form.value.checkCode);
          } else {
            uni.showToast({
              mask: true,
              title: `单据${form.value.checkCode}撤回失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          commentShow.value = false;
          comment.value = '';
          uni.hideLoading();
        });
    },
  });
};

// 审核信息
const onComplete = (status: number) => {
  if (status === 3 && !comment.value) {
    uni.showToast({
      title: '请填写审核意见',
      icon: 'none',
      mask: true,
    });
    return;
  }

  const params = {
    comment: comment.value,
    id: form.value.id,
    taskId: form.value.taskId,
    status,
  };
  uni.showLoading({
    title: '审核中',
    mask: true,
  });
  formComplete(assayType.value, params)
    .then((res) => {
      if (res.code === 0) {
        uni.showToast({
          title: '单据审核成功',
          icon: 'none',
          mask: true,
        });
        form.value.instanceId = '';
        init(form.value.id, form.value.checkCode);
        uni.$emit('assayFormRefresh', true);
        refreshFlow();
      } else {
        uni.showToast({
          mask: true,
          title: `单据审核失败，失败原因：${res.msg}`,
          icon: 'none',
        });
      }
    })
    .finally(() => {
      commentShow.value = false;
      comment.value = '';
      uni.hideLoading();
    });
};

const isCanCancelApprover = ref(false); // 是否能弃审
const getCancelApprover = () => {
  listLastNodePerson({
    processInstanceId: form.value.instanceId,
  })
    .then((res) => {
      const dataList = res.data;
      const { username } = userStore.userInfos.user;
      if (dataList.find((item) => item === username)) {
        isCanCancelApprover.value = true;
      } else {
        isCanCancelApprover.value = false;
      }
    })
    .finally(() => {});
};

const onRevive = () => {
  showModal({
    title: '提示',
    content: '是否弃审该单据',
    showCancel: true,
    confirm: () => {
      uni.showLoading({
        mask: true,
      });
      formRevive(assayType.value, {
        id: form.value.id,
        comment: comment.value,
      })
        .then((res) => {
          if (res.code === 0) {
            uni.showToast({
              mask: true,
              title: `弃审成功`,
              icon: 'none',
            });
            uni.$emit('assayFormRefresh', true);
            form.value.instanceId = '';
            nextTick(() => {
              init(form.value.id, form.value.checkCode);
            });
          } else {
            uni.showToast({
              mask: true,
              title: `弃审失败，失败原因：${res.msg}`,
              icon: 'none',
            });
          }
        })
        .finally(() => {
          commentShow.value = false;
          comment.value = '';
          uni.hideLoading();
        });
    },
  });
};

const statusList = [
  {
    text: '未提交',
    value: '0',
    color: '#108ee9',
  },
  {
    text: '审批中',
    value: '1',
    color: '#d46b08',
  },
  {
    text: '已审核',
    value: '2',
    color: '#87d068',
  },
  {
    text: '驳回',
    value: '3',
    color: '#f50',
  },
  {
    text: '撤回',
    value: '9',
    color: '#f50',
  },
];
const { bill_status } = useDict('bill_status');
const getStatus = (status) => {
  if (status == null)
    return {
      text: '未提交',
      value: '0',
      color: '#108ee9',
    };
  const o1 = statusList.find((item) => item.value == status);
  const o = bill_status.value.find((item) => item.value == status);
  return o
    ? {
        ...o,
        color: o1.color,
      }
    : { text: status };
};

const assayerNameShow = ref(false);
const assayerNames = ref('');
const showAssayerName = (value) => {
  assayerNameShow.value = true;
  assayerNames.value = value;
};
const changeEquiment = (record: any) => {
  record.equipmentEntities?.forEach((item) => {
    if (item.equipmentCode === record.equipmentCode) {
      record.equipmentName = item.equipmentName;
    }
  });
  // 获取化验员
  getAssayers(record.equipmentCode).then((res) => {
    record.assayerName = res.data
      .map((item: any) => {
        return item.nickName;
      })
      .join(',');
    record.assayerCode = res.data
      .map((item: any) => {
        return item.userCode;
      })
      .join(',');
  });
};

// const assayerCodeChange = (record) => {
//   const match = record.assayerOption.find((item) => {
//     return item.value === record.assayerCode;
//   });
//   record.assayerName = match.label;
// };

// 选择指标
const showItemName = ref(false);
const checkItemNam = ref(null);
const itemNamcolumns = ref([]);
const showItemNameList = (item, index) => {
  console.log(item);
  if (form.value.status !== 0) return;
  checkItemNam.value = null;
  if (!item.analysisId) {
    uni.showToast({
      title: '请先选择检测项目（分析手段）',
      icon: 'none',
      mask: true,
    });
    return;
  }
  const o = analysisOptions.value.find((a) => a.value === item.analysisId);
  if (!o) {
    uni.showToast({
      title: '没有检测指标,请输入',
      icon: 'none',
    });
    return;
  }
  itemNamcolumns.value = o.analysisIndexEntityList.map((item) => {
    return {
      name: item.analysisIndex,
      valueType: item.valueType,
    };
  });
  checkItemNam.value = index;
  showItemName.value = true;
};

const closeItemNam = () => {
  showItemName.value = false;
};
const selectItemNam = (e) => {
  const { name, valueType } = e.item;
  form.value[assayKey.value][checkItemNam.value].itemName = name;
  form.value[assayKey.value][checkItemNam.value].valueType = valueType;
  checkItemNam.value = null;
};

const addRow = () => {
  form.value[assayKey.value].push({
    analysisName: '',
    analysisId: '',
    unit: undefined,
    equipmentName: '',
    equipmentEntities: [],
    analysisIndexUnitList: [],
    indexEntities: [],
    remark: '',
    editFlag: 1,
  });
};

const copyRow = (record, index) => {
  const {
    analysisName,
    analysisId,
    unit,
    indexEntities,
    equipmentEntities,
    analysisIndexUnitList,
  } = record;
  form.value[assayKey.value].splice(index + 1, 0, {
    analysisName,
    analysisId,
    unit,
    equipmentName: '',
    equipmentEntities,
    indexEntities,
    analysisIndexUnitList,
    remark: '',
    editFlag: 1,
  });
};

const delRow = (record, index) => {
  if (assayType.value === 'qcMiddleCheck') {
    if (!record.editFlag) return;
    if (form.value[assayKey.value].length > 1) {
      form.value[assayKey.value].splice(index, 1);
    }
  } else {
    if (!record.editFlag) return;
    const match = form.value[assayKey.value].filter((item) => {
      return item.analysisId === record.analysisId;
    });

    if (match.length > 1 || !record.analysisId || record.editFlag === 1) {
      form.value[assayKey.value].splice(index, 1);
    }
  }

  // if (form.value[assayKey.value].length > 1) {
  //   uni.showModal({
  //     title: '提示',
  //     content: '是否删除该检测项目',
  //     showCancel: true,
  //     success: ({ confirm, cancel }) => {
  //       if (cancel) {
  //         return;
  //       }
  //       form.value[assayKey.value].splice(index, 1);
  //     },
  //   });
  // }
};
</script>

<style lang="scss" scoped>
.actions-bar {
  padding: 8rpx 15rpx;
  background: #fff;
  border-bottom: 1rpx solid #dedede;

  .btn {
    border: none;
  }

  text {
    font-size: 24rpx;
    color: #dedede;
  }
}

.card-detail {
  padding: 0 !important;
}

.wd-cell {
  padding-left: 0 !important;
}

.wd-card__title {
  border-left: 4px solid #2e5cf6 !important;
}

:deep(.label) {
  width: 160rpx !important;
}

.seq-no-text {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  word-break: break-all;
  word-wrap: break-word;
}

.flow-btn-fixed {
  width: 100%;
  background-color: white;
  border-top: 1px solid #f2f2f1;
}

.btn_group {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #f1f1f1;

  .btn {
    display: flex;
    flex: 1;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 40px;
    padding: 10rpx 0;
    color: black;

    // background-color: #dbecff !important;
    border-left: 1px solid #f1f1f1;
    border-radius: 0 !important;
    border-radius: 6rpx;

    .btn-icon {
      width: 40rpx;
      height: 40rpx;
      margin-bottom: 8rpx;
    }
  }

  .danger {
    background-color: #f56c6c;
  }

  .primary {
    background-color: #409eff;
  }
}

.assay-name {
  position: relative;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
